
import 'dart:math' as math;
import 'package:flutter/rendering.dart';

//一饮而尽流委托
class CarouseFlowDelegate extends FlowDelegate{

  final ViewportOffset viewportOffset;//显示窗口抵消
  final int filtersPerScreen;//过滤器屏幕

  //一定要 实现父类方法
  CarouseFlowDelegate({
    required this.viewportOffset,
    required this.filtersPerScreen
  }): super(repaint: viewportOffset);

  //画画的孩子 (流背景)
  @override
  void paintChildren(FlowPaintingContext context) {

    final count = context.childCount;
    final size = context.size.width;
    //item范围
    final itemExtent = size / filtersPerScreen;

    //积极的、活跃的
    final active = viewportOffset.pixels / itemExtent;
    final min = math.max(0, active.floor() -3).toInt();
    final max = math.min(count - 1, active.ceil() + 3).toInt();//向上取整

    for(var index = min; index <= max; index++) {
      //项目X来自中心
      final itemXFromCenter = itemExtent * index - viewportOffset.pixels;
      //百分比从中心
      final percentFromCenter = 1.0 - (itemXFromCenter / (size / 2)).abs();
      //项目规模
      final itemScale = 0.5 + (percentFromCenter * 0.5);
      //不透明
      final opacity = 0.25 + (percentFromCenter * 0.75);

      //项反式
      final itemTransform = Matrix4.identity()
        ..translate((size - itemExtent) / 2)//编译、使转变
        ..translate(itemXFromCenter)
        ..translate(itemExtent / 2, itemExtent / 2)
        ..multiply(Matrix4.diagonal3Values(itemScale, itemScale, 1.0))//大大增加
        ..translate(-itemExtent / 2, -itemExtent / 2);

      context.paintChild(
        index,
        transform: itemTransform,
        opacity: opacity,
      );
    }
  }

  //重新绘制(一饮而尽流委托)
  @override
  bool shouldRepaint(covariant CarouseFlowDelegate oldDelegate) {
    return oldDelegate.viewportOffset != viewportOffset;
  }

}

